<template>
  <pageTabelLayout>
    <template #pageHeader>
      <div class="search-form divClass" v-if="headerShow" style="margin-top: 15px">
        <div>
          <a-form size="small" :model="pageData" layout="inline" ref="formRef">
            <CorporateSectorCascader
              ref="cascaderRef"
              :configCascader="configCascader"
              @changeCascader="changeCascader"
            />
            <a-form-item
              label="月份"
              field="recordDate"
              :validate-trigger="['change', 'blur']"
              :rules="[{ required: true, message: '月份必填' }]"
            >
              <a-month-picker
                :style="{ width: '220px' }"
                class="bacClass"
                v-model="pageData.recordDate"
                @press-enter="huiche"
                @change="isCurrentMonth"
              />
            </a-form-item>
            <a-form-item label="原料编号">
              <a-input
                allow-clear
                :style="{ width: '220px' }"
                class="bacClass"
                v-model="pageData.yarnCode"
                @press-enter="huiche"
              />
            </a-form-item>
            <a-form-item label="原料名称">
              <a-input
                allow-clear
                :style="{ width: '220px' }"
                class="bacClass"
                v-model="pageData.yarnName"
                @press-enter="huiche"
              />
            </a-form-item>
          </a-form>
        </div>
        <div class="my-divisders">
          <Toolbar
            class="gesture"
            :items="['查询', '导出']"
            @select="selectHandler"
            @export="exports"
          ></Toolbar>
        </div>
      </div>
      <div class="my-divisders">
        <a-divider orientation="center">
          <icon-double-up
            v-if="headerShow"
            @click="headerShow = false"
            :strokeWidth="2"
            :size="18"
          />
          <icon-double-down v-else @click="headerShow = true" :strokeWidth="2" :size="18" />
        </a-divider>
      </div>
    </template>
    <template #pageTabel>
      <div style="float: right">
        <a-button
          class="countButton"
          type="primary"
          size="mini"
          @click="updateYarn(0)"
          :disabled="!pageData.isClick"
          >盘点时，点击获取原纱仓实际库存为原纱仓盘点重量</a-button
        >
        <a-button
          class="countButton"
          type="primary"
          size="mini"
          @click="updateYarn(1)"
          :disabled="!pageData.isClick"
          >盘点时，点击获取验后未入库拆纱重量&ensp;&ensp;&ensp;&ensp;</a-button
        >
        <a-button
          class="countButton"
          type="primary"
          size="mini"
          @click="updateYarn(2)"
          :disabled="!pageData.isClick"
          >盘点时，点击获取坯布库存换算为拆纱重量</a-button
        >
      </div>
      <a-spin
        :loading="pageData.pageLoading"
        tip="加载中"
        dot
        style="height: 100%; width: 100%; z-index: 999"
      >
        <AgGridVuesCopys
          :rowHeight="33"
          :headerHeight="33"
          rowSelection="multiple"
          @grid-ready="gridReady"
          style="height: 97%"
          :defaultColDef="defaultColDef"
          :suppressCopyRowsToClipboard="true"
          class="ag-theme-alpine"
          :rowData="pageData.tableList"
          :columnDefs="tableColumns"
          :localeText="localeText1"
          @FilterChanged="FilterChangeds"
        >
        </AgGridVuesCopys>
      </a-spin>
    </template>
    <paginationCopys
      :page-size-options="pagingList1"
      :total="total"
      :page-size="size"
      :current="page"
      @change="PageSize"
      @page-size-change="change1"
      show-total
      show-jumper
      show-page-size
      style="justify-content: center"
    />
  </pageTabelLayout>
</template>

<script lang='ts' setup>
import { reactive, toRefs, ref, onMounted } from 'vue'
import Toolbar from '@/components/Toolbar.vue'
import { post, get } from '@/api/http'
import { Message, Modal } from '@arco-design/web-vue'

import { localeText } from '@/api/aggridZw'
import { pagingList } from '@/api/paging'
import { assTable } from '@/utils/assemblyLevelTable'
import { FormInstance } from '@arco-design/web-vue/es/form'
import CorporateSectorCascader from '@/components/corporateSectorCascader/inde.vue'

const pagingList1: any = ref(pagingList)
const localeText1: any = ref(localeText)
const headerShow = ref<boolean>(true)
const pageData: any = reactive({
  isClick: false,
  rHeight: 0,
  tableList: [],
  pageLoading: false,
  firmId: null,
  recordDate: '',
  yarnCode: '',
  yarnName: '',
})

const defaultColDef: any = {
  sortable: true,
  resizable: true,
  filter: true,
}
const gridOption = ref()
const colState = ref()
const gridReady = (params: any) => {
  gridOption.value = params.api
  colState.value = params.columnApi
}

const tableColumns: any = [
  { headerName: '公司', field: 'firm', width: 150 },
  { headerName: '客户名称', field: 'customName', width: 150 },
  { headerName: '原纱编号', field: 'yarnCode', width: 150 },
  { headerName: '原纱名称', field: 'yarnName', width: 150 },
  { headerName: '纱牌', field: 'yarnBrand', width: 150 },
  { headerName: '纱批', field: 'productionBatch', width: 150 },
  { headerName: '色号', field: 'colorCode', width: 150 },
  { headerName: '色称', field: 'colorName', width: 150 },
  { headerName: '原纱仓盘点重量', field: 'stockWeight', width: 150 },
  { headerName: '验后未入库拆纱重量', field: 'qmsWeight', width: 150 },
  { headerName: '车间盘点重量', field: 'workshopWeight', width: 150 },
  { headerName: '坯布库存拆纱重量', field: 'greyWeight', width: 150 },
  { headerName: '实际结存重量', field: 'totalWeight', width: 150 },
]

//分页
const total = ref(0)
const page = ref(1)
const size = ref(10)
function PageSize(val: any) {
  page.value = val
  doRefresh()
}
function change1(val: any) {
  size.value = val
  doRefresh()
}

//查询
const formRef = ref<FormInstance>()
const doRefresh = () => {
  formRef.value?.validate().then((err: any) => {
    if (!err) {
      pageData.pageLoading = true
      post({
        url: '/wms/yarnBalance/getPageYarnBalance',
        data: {
          page: page.value,
          size: size.value,
          firmId: pageData.firmId,
          recordDate: pageData.recordDate,
          yarnCode: pageData.yarnCode,
          yarnName: pageData.yarnName,
        },
      })
        .then(({ data, code }: any) => {
          if (code === 200) {
            pageData.tableList = data.list
            gridOption.value.setRowData(data.list)
            total.value = data.total
            counts(pageData.tableList)
          }
        })
        .catch(console.log)
        .finally(() => {
          pageData.pageLoading = false
        })
    }
  })
}

const selectHandler = () => {
  page.value = 1
  doRefresh()
}

const huiche = () => {
  doRefresh()
}

//更新本月结存数据
const updateYarn = (num: any) => {
  formRef.value?.validate().then((err: any) => {
    if (!err) {
      pageData.pageLoading = true
      post({
        url: '/wms/yarnBalance/updateYarnBalanceByType',
        data: {
          page: page.value,
          size: size.value,
          firmId: pageData.firmId,
          recordDate: pageData.recordDate,
          yarnCode: pageData.yarnCode,
          yarnName: pageData.yarnName,
          updateType: num,
        },
      })
        .then(({ data, code }: any) => {
          if (code === 200) {
            pageData.tableList = data.list
            gridOption.value.setRowData(data.list)
            total.value = data.total
            counts(pageData.tableList)
          }
        })
        .catch(console.log)
        .finally(() => {
          pageData.pageLoading = false
        })
    }
  })
}

//合计
const counts = (data:any) => {
  var sum1 = 0
  var sum2 = 0
  var sum3 = 0
  var sum4 = 0
  var sum5 = 0
  for (var i = 0; i < data.length; i++) {
    sum1 = sum1 + data[i].stockWeight
    sum2 = sum2 + data[i].qmsWeight
    sum3 = sum3 + data[i].workshopWeight
    sum4 = sum4 + data[i].greyWeight
    sum5 = sum5 + data[i].totalWeight
  }
  var nowRows = [
    {
      firm: '合计',
      stockWeight: sum1.toFixed(2),
      qmsWeight: sum2.toFixed(2),
      workshopWeight: sum3.toFixed(2),
      greyWeight: sum4.toFixed(2),
      totalWeight: sum5.toFixed(2),
    },
  ]
  gridOption.value.setPinnedBottomRowData(nowRows)
}

const FilterChangeds = (params: any) => {
  let data: any = {
    data: [],
  }
  params.api.forEachNodeAfterFilter((row: any) => {
    data.data.push(row.data)
  })
  counts(data.data)
}

//导出
const exports = () => {
  let nowRow = pageData.tableList.map((row: any) => {
        Object.keys(row).forEach(key => {
            if (row[key] === 0) {
                row[key] = '0';
            }
        });
        return row;
    });
  assTable(tableColumns, nowRow, '余料结存表')
}

//是否当前月份
function isCurrentMonth() {
  const selectedDate = new Date(pageData.recordDate)
  const currentDate = new Date()
  if (
    selectedDate.getFullYear() === currentDate.getFullYear() &&
    selectedDate.getMonth() === currentDate.getMonth()
  ) {
    pageData.isClick = true
  } else {
    pageData.isClick = false
  }
}

//公司
let cascaderRef = ref()
const configCascader = ref<{}>({
  corporateWidth: '220px', //公司宽度
  corporateRquired: true, //公司是否必填
  size: 'small', //选择框大小'mini' | 'small' | 'medium' | 'large'
  corporateName: '公司', //公司label
  cascaderShow: 'sector', //配置部门不显示
})
const changeCascader = (data: any) => {
  const { corporateId, corporateLabel } = data
  pageData.firmId = corporateId
}

//根据账号回显
const user = () => {
  post({
    url: '/admin/acl/user/findUserToken',
  }).then((res) => {
    post({
      url: 'admin/acl/user/findUserToken',
      data: {
        name: res,
      },
    }).then((res: any) => {
      if (res.code === 200) {
        let data: any = {
          corporateId: res.data.data.firmId,
          corporateLabel: res.data.data.firmName,
        }
        changeCascader(data)
        cascaderRef.value?.parentComponent({
          corporateId: res.data.data.firmId,
        })
      } else {
        Message.error({
          content: res.message,
          duration: 5000,
        })
      }
    })
  })
}

onMounted(() => {
  pageData.rHeight = document.getElementsByClassName('main-section')[0]?.clientHeight
  //弹出层的高
  if (pageData.rHeight !== undefined) {
    pageData.rHeight = pageData.rHeight
  }
  user()
})
</script>
<style lang='less' scoped>
:deep(.ag-cell) {
  border-right: 1px solid #dde2eb;
}

:deep(.ag-header-cell) {
  border-right: 1px solid #dde2eb;
}

:deep(.ag-cell-value) {
  user-select: initial;
  -moz-user-select: text;
  -ms-user-select: text;
  -webkit-user-select: text;
}

:deep(.arco-table-td-content) {
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}

.countButton {
  margin-right: 23px;
  border: 1px solid black;
  border-radius: 5px;
}
</style>